package com.example.demo.web.sessionfilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author wangsl
 * @date 2020/6/20 22:38
 * <p>
 * Description:
 *  过滤器的配置有2种方式,第一种是纯注解的方式,第二种是写过滤器注册配置类,这里使用了第二种
 *  1.在过滤器上添加WebFilter注解
 *    在启动类SpringbootApplication添加ServletComponentScan注解
 *  2.通过过滤器注册配置类使用过滤器(WebComponent2Config)
 */

//@WebFilter(filterName = "sessionFilter",urlPatterns = {"/*"})
public class SessionFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession(false);
        String uri = request.getRequestURI();
        //标示符：表示当前用户未登录(可根据自己项目需要改为json样式)
        String NO_LOGIN = "您还未登录";
        String REQ_PREFIX = request.getContextPath();
        //不需要登录就可以访问的路径(比如:注册登录等)
        String[] includeUrls = new String[]{REQ_PREFIX + "/login",
                REQ_PREFIX + "/register", REQ_PREFIX + "/user/login.html"};

        System.out.println("filter url:"+uri);
        //是否需要过滤
        boolean needFilter = isNeedFilter(uri, includeUrls);
        if (!needFilter) { //不需要过滤直接传给下一个过滤器
            filterChain.doFilter(servletRequest, servletResponse);
        } else { //需要过滤器
            // session中包含user对象,则是登录状态
            if(session!=null&&session.getAttribute("user") != null){
                // System.out.println("user:"+session.getAttribute("user"));
                filterChain.doFilter(request, response);
            }else{
                String requestType = request.getHeader("X-Requested-With");
                //判断是否是ajax请求
                if(requestType!=null && "XMLHttpRequest".equals(requestType)){
                    response.getWriter().write(NO_LOGIN);
                }else{
                    //重定向到登录页(需要在static文件夹下建立此html文件)
                    response.sendRedirect(request.getContextPath()+"/user/login.html");
                }
                return;
            }
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }

    /**
     * @author wangsl
     * @date 2020/6/20 22:46
     * Description:是否需要过滤
     */
    public boolean isNeedFilter(String uri, String[] includeUrls) {
        for (String includeUrl : includeUrls) {
            if (includeUrl.equals(uri)) {
                return false;
            }
        }
        return true;
    }
}